import {Component, NgZone, ViewChild} from '@angular/core';
import {
  Content,
  Events,
  InfiniteScroll,
  IonicPage,
  ModalController,
  NavController,
  NavParams,
  PopoverController
} from 'ionic-angular';
import {Util} from "@providers/util";
import {PagingConfig, PagingProvider} from "@providers/paging";
import {StorageProvider} from "@providers/storage";
import {DialogProvider} from "@providers/dialog";
import {HttpProvider} from "@providers/http";
import {ManagerProvider} from "@providers/interface/manager";
import {NativeProvider} from "@providers/natives/native";

/**
 * Generated class for the MdispatchPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-manager-order',
  templateUrl: 'manager-order.html',
})
export class ManagerOrderPage {
  @ViewChild(Content) content: Content;
  userInfo: any;
  datas: any[] = [];
  datasConfig: PagingConfig = new PagingConfig();
  datasNum = 0;//单据数量
  status: any;//工单流程，默认待派工
  canScrollToTop: boolean = false;//是否显示返回到顶部按钮
  param = this.navParams.data;

  constructor(public navCtrl: NavController,
              public navParams: NavParams,
              private pagingService: PagingProvider,
              private storageService: StorageProvider,
              private modalCtrl: ModalController,
              private dialog: DialogProvider,
              private http: HttpProvider,
              private zone: NgZone,
              private events: Events,
              private popoverCtrl: PopoverController,
              private manager: ManagerProvider,
              private native: NativeProvider) {
    this.userInfo = this.storageService.read('userInfo');
    this.events.subscribe('ManagerOrderPage', () => {
      if (this.native.isMobile()) {
        this.refresh();
      }
    });
    let statuses = (this.userInfo.GW || []).filter(value => {
      return value.KEY == 'YW';
    });
    this.status = this.navParams.get('status') ||
      (statuses.length > 0 ? statuses[0].VALUE[0] : {
        KEY: 'DPG',
        VALUE: '待派工'
      });
  }

  ionViewDidLoad() {
    this.getOrdersNum();
    this.refresh();
  }

  ionViewWillEnter() {
    this.userInfo = this.storageService.read("userInfo");
    if (!this.native.isMobile()) {
      this.refresh();
    }
  }

  push(page: string, data?: any) {
    this.navCtrl.push(page, data);
  }

  /**
   * 滑动时触发
   */
  scrollContent() {
    this.zone.run(() => {
      let scrollTop = this.content.getContentDimensions().scrollTop;
      if (scrollTop > 400) {
        this.canScrollToTop = true;
      } else {
        this.canScrollToTop = false;
      }
    })
  }

  //更改订单状态，弹出弹窗
  changeOrderStatus(myEvent) {
    let popover = this.popoverCtrl.create('ManagerStatusChoosePage', this.status, {cssClass: 'order_list_page'});
    popover.onDidDismiss(data => {
      if (data) {
        this.status = data;
        this.getOrdersNum();
        this.refresh();
      }

    });
    popover.present({
      ev: myEvent
    });
  }

  //获取单据数量
  getOrdersNum() {
    this.http.post("/Inbound/invoke.do", {
      interfaceId: "csm.css.getgdtj",
      data: JSON.stringify({
        "GDLC": this.status.KEY,
        "RYXX01": this.userInfo.RYXX01,
        "searchText": this.param['searchText'],
        "YYSJ": this.param['YYSJ'],
        "djly": this.param['DJLY'],
        "DDZT": this.param['DDZT'],
        "DJLX": this.param['DJLX']
      })
    }).subscribe(message => {
      this.datasNum = message.data.SL;
    }, error => {
      this.dialog.showAlert('请检查网络！' + error);
    });
  }

  /**
   * 抢单点击事件
   */
  grabOrders(data: any, index: number) {
    this.dialog.showConfirm(() => {
      this.dialog.showLoading();
      let temp = [];
      temp.push(data.ID);
      this.manager.managerGrabsorder(temp)
        .then(message => {
          data.STATUSID = 'GRABED';
          this.dialog.hideLoading();
        })
        .catch(error => {
          this.dialog.showAlert('抢单派工失败！' + error);
          this.dialog.hideLoading();
        });
    }, '是否执行抢单派工操作？');
  }

  /**
   * 派工
   */
  dispatch(data: any, index: number) {
    let a = {};
    a['WD'] = data.PROVIDER;
    if (data.SERVICETYPEID == 1) {
      a['shlx'] = '1';
    } else {
      a['fwlx'] = '1';
    }
    let modal = this.modalCtrl.create('ManagerMworksPage', a);
    modal.onDidDismiss(value => {
      if (value) {
        let temp = {};
        temp['ZCR'] = this.userInfo.RYXX02;
        if (data.SERVICETYPEID == 1) {
          temp['XZSHRYDM'] = value.KEY;
          temp['XZSHRY'] = value.VALUE;
        } else {
          temp['FWRYDM'] = value.KEY;
          temp['FWRY'] = value.VALUE;
        }
        temp['LIST'] = [];
        temp['LIST'].push({"GD01": data.ID});
        this.dialog.showLoading();
        this.http.post("/Inbound/invoke.do", {
          interfaceId: "csm.css.jcdy.cssorderjk.jx",
          data: JSON.stringify(temp)
        }).subscribe(message => {
          this.datas.splice(index, 1);
          this.dialog.hideLoading();
          this.getOrdersNum();
        }, error => {
          this.dialog.showAlert('派工失败！' + error);
          this.dialog.hideLoading();
        });
      }
    });
    modal.present();
  }

  /**
   * 刷新数据
   */
  refresh(refresher?: any) {
    this.getOrdersNum();
    this.datasConfig = new PagingConfig();
    this.getData(data => {
      this.datas = data;
      if (refresher) {
        setTimeout(() => {
          refresher.complete();
        }, 500);
      }
    }, this.datasConfig, error2 => {
      if (refresher) {
        setTimeout(() => {
          refresher.complete();
        }, 500);
      }
    });
  }

  //上拉刷新事件
  getMoreDatas(infiniteScroll: InfiniteScroll) {
    this.getData((value) => {
      this.datas.push.apply(this.datas, value);
      infiniteScroll.complete();
    }, this.datasConfig);
  }

  /**
   * 获取数据
   * @param pagingConfig 分页
   * @param fn 方法
   * @param errorFun 方法
   */
  private getData(fn: (value) => void, pagingConfig, errorFun?: (error) => void) {
    this.pagingService.get({
      interfaceId: "csm.som.cssOrderquery.selectSOrder",
      data: {
        "RYXX01": this.userInfo.RYXX01,
        "GDLC": this.status.KEY,
        "searchText": this.param['searchText'],
        "YYSJ": this.param['YYSJ'],
        "DJLY": this.param['DJLY'],
        "DDZT": this.param['DDZT'],
        "DJLX": this.param['DJLX']
      }
    }, pagingConfig).subscribe(data => {
      for (let i = 0; i < data.length; i++) {
        let v = data[i];
        let d: Date = new Date(v.THRUTIME);
        if (!isNaN(v.THRUTIME)) {
          v.THRUTIME = Util.dateFormat(d, "yyyy-MM-dd")
        }
      }
      fn(data);
    }, error => {
      if (errorFun) {
        errorFun(error);
      }
    });
  }
}
